<!-- eslint-disable vue/valid-v-slot -->
<template>
  <div class="main-container">
    <TableBody>
      <template #header>
        <TableHeader ref="tableHeaderRef" :show-filter="false">
          <template #search-content>
            <a-form ref="serchForm" :model="form">
              <a-row :gutter="24">
                <a-col :span="4">
                  <a-form-item field="name" hide-label>
                    <a-input v-model="form.name" placeholder="请输入角色名称" allow-clear />
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="state" hide-label>
                    <a-select v-model="form.close" placeholder="请选择角色状态" allow-clear>
                      <a-option value="0">正常</a-option>
                      <a-option value="1">关闭</a-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="addTime" hide-label>
                    <a-date-picker
                      v-model="form.addTime"
                      style="width: 100%"
                      show-time
                      placeholder="请选择开始创建时间"
                      :time-picker-props="{ defaultValue: '12:00:00' }"
                      format="YYYY-MM-DD HH:mm:ss"
                      allow-clear
                      :shortcuts="[
                        {
                          label: '今日',
                          value: () => (
                            (form.addTime = $dayjs('00:00:00', 'HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            )),
                            (form.endTime = $dayjs('23:59:59', 'HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            ))
                          ),
                        },
                        {
                          label: '昨日',
                          value: () => (
                            (form.addTime = $dayjs('00:00:00', 'HH:mm:ss')
                              .subtract(1, 'day')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (form.endTime = $dayjs('23:59:59', 'HH:mm:ss')
                              .subtract(1, 'day')
                              .format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '七日',
                          value: () => (
                            (form.addTime = $dayjs('00:00:00', 'HH:mm:ss')
                              .subtract(6, 'day')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (form.endTime = $dayjs().format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '本月',
                          value: () => (
                            (form.addTime = $dayjs('01 00:00:00', 'DD HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            )),
                            (form.endTime = $dayjs().format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '上月',
                          value: () => (
                            (form.addTime = $dayjs(`01 00:00:00`, 'DD HH:mm:ss')
                              .subtract(1, 'month')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (form.endTime = $dayjs()
                              .subtract(1, 'month')
                              .endOf('month')
                              .format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                      ]"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="endTime" hide-label>
                    <a-date-picker
                      v-model="form.endTime"
                      show-time
                      style="width: 100%"
                      placeholder="请选择结束创建时间"
                      :time-picker-props="{ defaultValue: '12:00:00' }"
                      format="YYYY-MM-DD HH:mm:ss"
                      allow-clear
                      :shortcuts="[
                        {
                          label: '今日',
                          value: () => (
                            (form.addTime = $dayjs('00:00:00', 'HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            )),
                            (form.endTime = $dayjs('23:59:59', 'HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            ))
                          ),
                        },
                        {
                          label: '昨日',
                          value: () => (
                            (form.addTime = $dayjs('00:00:00', 'HH:mm:ss')
                              .subtract(1, 'day')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (form.endTime = $dayjs('23:59:59', 'HH:mm:ss')
                              .subtract(1, 'day')
                              .format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '七日',
                          value: () => (
                            (form.addTime = $dayjs('00:00:00', 'HH:mm:ss')
                              .subtract(6, 'day')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (form.endTime = $dayjs().format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '本月',
                          value: () => (
                            (form.addTime = $dayjs('01 00:00:00', 'DD HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            )),
                            (form.endTime = $dayjs().format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '上月',
                          value: () => (
                            (form.addTime = $dayjs(`01 00:00:00`, 'DD HH:mm:ss')
                              .subtract(1, 'month')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (form.endTime = $dayjs()
                              .subtract(1, 'month')
                              .endOf('month')
                              .format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                      ]"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="btns" hide-label>
                    <a-space :size="15">
                      <a-button
                        type="primary"
                        v-permission="getRoleLists"
                        html-type="submit"
                        @click="doRefresh(1)"
                        ><template #icon>
                          <icon-search />
                        </template>
                        <!-- Use the default slot to avoid extra spaces -->
                        <template #default>搜索</template></a-button
                      >
                      <a-button v-permission="getRoleLists" @click="resetSeach"
                        ><template #icon>
                          <icon-sync theme="outline" size="14" />
                        </template>
                        <!-- Use the default slot to avoid extra spaces -->
                        <template #default>重置</template></a-button
                      >
                    </a-space>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </template>
        </TableHeader>
      </template>
      <template #table-config>
        <a-space :size="15">
          <a-button type="primary" v-permission="postAddRole" @click="onAddItem">
            <!-- Use the default slot to avoid extra spaces -->
            <template #default>新建</template>
          </a-button>
          <a-button
            type="outline"
            v-permission="exportRoleList"
            @click="exportLists"
            :loading="loading"
          >
            <!-- Use the default slot to avoid extra spaces -->
            <template #default>导出</template>
          </a-button>
        </a-space>
        <a-space :size="15">
          <TableConfig
            @update-border="onUpdateBorder"
            @update-striped="onUpdateStriped"
            @refresh="doRefresh"
          />
        </a-space>
      </template>
      <template #default>
        <a-table
          :bordered="{ wrapper: true, cell: bordered }"
          :stripe="(striped as boolean)"
          :loading="tableLoading"
          :data="dataList"
          :pagination="false"
          :column-resizable="true"
          :rowKey="rowKey"
          :columns="tableColumns.list"
          :scrollbar="true"
          table-layout-fixed
        >
          <template #columns>
            <a-table-column
              v-for="item of tableColumns.list"
              :key="item.key"
              align="left"
              :width="100"
              :ellipsis="true"
              :tooltip="true"
              :title="(item.title as string)"
              :data-index="(item.key as string)"
            >
              <template v-if="item.key === 'index'" #cell="{ rowIndex }">
                {{ rowIndex + 1 }}
              </template>
              <template v-else-if="item.key === 'actions'" #cell="{ record }">
                <a-space :size="2">
                  <a-button
                    v-permission="postUpdateRole"
                    style="padding: 0px 4px"
                    type="text"
                    @click="onUpdate(record)"
                    size="small"
                    >编辑</a-button
                  >
                  <a-button
                    v-permission="postSetRole"
                    style="padding: 0px 4px"
                    @click="showTree(record)"
                    type="text"
                    size="small"
                  >
                    权限
                  </a-button>
                  <a-button
                    v-permission="getdelRole"
                    style="padding: 0px 4px"
                    type="text"
                    size="small"
                    @click="onDeleteItem(record)"
                  >
                    删除
                  </a-button>
                </a-space>
              </template>
              <template v-else-if="item.key === 'close'" #cell="{ record }">
                <a-tag color="blue" size="small" v-if="record.close === false">正常</a-tag>
                <a-tag color="red" size="small" v-else-if="record.close === true">关闭</a-tag>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </template>
      <template #footer>
        <TableFooter ref="tableFooterRef" :pagination="pagination" />
      </template>
    </TableBody>
    <a-modal
      v-model:visible="visible"
      @before-close="handleCancel"
      :title="dialogTitle"
      width="600px"
      :mask-closable="false"
      title-align="start"
    >
      <a-form ref="userForm" :auto-label-width="true" :model="subForm">
        <a-form-item
          label="角色名称"
          field="name"
          :rules="[
            { required: true, message: '角色名称不能为空' },
            { minLength: 1, maxLength: 15, message: '角色名称必须小于15个字符' },
          ]"
          :validate-trigger="['change', 'input']"
          asterisk-position="end"
        >
          <a-input v-model.trim="subForm.name" placeholder="请输入角色名称" allow-clear />
        </a-form-item>
        <!-- <a-form-item
          label="角色排序"
          field="sort"
          :rules="[{ required: true, message: '角色排序不能为空' }]"
          :validate-trigger="['change', 'input']"
        >
          <a-input-number v-model.trim="subForm.sort" placeholder="请输入角色排序" allow-clear />
        </a-form-item> -->
        <a-form-item field="single" label="角色状态">
          <a-radio-group class="radio-bcg" v-model="subForm.close">
            <a-radio :value="false">
              <template #radio="{ checked }">
                <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot"></div> </div
                  ><div className="custom-radio-card-title">正常</div>
                </div>
              </template>
            </a-radio>
            <a-radio :value="true">
              <template #radio="{ checked }">
                <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot"></div> </div
                  ><div className="custom-radio-card-title">关闭</div>
                </div>
              </template>
            </a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item field="remarks" label="备注" asterisk-position="end">
          <a-textarea v-model="subForm.remarks" placeholder="请输入备注" allow-clear />
        </a-form-item>
      </a-form>
      <template #footer>
        <a-space>
          <a-button @click="handleCancel">取消</a-button>
          <a-button type="primary" @click="handleBeforeOk">确定</a-button>
        </a-space>
      </template>
    </a-modal>
    <a-modal
      v-model:visible="balancevisible"
      @before-close="handleCancelBan"
      width="500px"
      title="权限设置"
      :mask-closable="false"
      title-align="start"
    >
      <!-- <template #title style="display: flex; justify-content: space-between">
        权限设置 <icon-fullscreen
      /></template> -->
      <a-spin :loading="loadingTree" tip="加载中····" style="width: 100%">
        <a-tabs v-model:active-key="active" @change="tab" :default-active-key="1">
          <a-tab-pane title="菜单权限" :key="1">
            <a-scrollbar style="overflow: auto">
              <a-input-search
                placeholder="请输入地址名称"
                style="margin-bottom: 8px; width: 100%"
                v-model="searchKey"
              />
              <a-tree
                :virtualListProps="{
                  height: 600,
                }"
                :checkable="true"
                checked-strategy="all"
                tree-checked-strategy="all"
                v-model:checked-keys="selectList"
                :data="treeData"
                :field-names="{ key: 'route', title: 'name' }"
                :expanded-keys="mergedExpandedKeys"
                @expand="handleExpand"
                ><template #title="nodeData">
                  <template v-if="((index = getMatchIndex(nodeData?.name)), index < 0)"
                    >{{ nodeData?.name }}
                    <span v-if="nodeData.show == true" style="color: #349efa"> 首页 </span>
                    <span
                      v-else-if="nodeData.show == false"
                      @click="sys(nodeData)"
                      style="color: #86909c"
                    >
                      设置首页
                    </span>
                    <span v-else-if="nodeData.show == 2"> </span
                  ></template>
                  <span v-else>
                    {{ nodeData?.name?.substr(0, index) }}
                    <span style="color: var(--color-primary-light-4)">
                      {{ nodeData?.name?.substr(index, searchKey.length) }} </span
                    >{{ nodeData?.name?.substr(index + searchKey.length) }}
                  </span>
                </template>
              </a-tree>
            </a-scrollbar>
          </a-tab-pane>
          <a-tab-pane title="插件权限" :key="2"
            ><a-scrollbar style="height: 600px; overflow: auto">
              <a-tree
                :checkable="true"
                :default-expand-all="true"
                checked-strategy="child"
                v-model:checked-keys="selectList2"
                :data="treeData2"
                :expanded-keys="treeData2Key"
                :field-names="{ key: 'route', title: 'name' }"
                @expand="expands"
              /> </a-scrollbar
          ></a-tab-pane>
          <a-tab-pane :key="3">
            <template #title>其他权限</template>
            <a-scrollbar style="height: 600px; overflow: auto">
              <a-tree
                :checkable="true"
                checked-strategy="child"
                v-model:checked-keys="selectList3"
                :data="treeData3"
                :field-names="{ key: 'route', title: 'name' }"
              />
            </a-scrollbar>
          </a-tab-pane>
        </a-tabs>
      </a-spin>
      <template #footer>
        <div
          style="display: flex; justify-content: space-between; width: 100%; align-items: center"
        >
          <div>
            <span style="color: #349efa; cursor: pointer" @click="quanFn">全选</span>
            <span style="color: #86909c; margin-left: 10px; cursor: pointer" @click="fanFn"
              >反选</span
            ><span style="color: #86909c; margin-left: 10px; cursor: pointer" @click="zhanFn"
              >一键展开</span
            >
          </div>
          <div>
            <a-button @click="handleCancelBan">取消</a-button>
            <a-button type="primary" style="margin-left: 10px" @click="handleBeforeOkBan"
              >确定</a-button
            >
          </div>
        </div>
      </template>
    </a-modal>
  </div>
</template>

<script lang="ts">
  import useCommonStore from '@/store/modules/common'
  import * as http from '@/api/http'

  import {
    postAddRole,
    postUpdateRole,
    getdelRole,
    getRoleLists,
    getTree,
    exportRoleList,
    postSetRole,
  } from '@/api/url'
  import {
    usePagination,
    useRowKey,
    useRowSelection,
    useTable,
    useTableHeight,
  } from '@/hooks/table'

  import type { ModalDialogType } from '@/types/components'
  import { Form, Message, Modal } from '@arco-design/web-vue'
  import { computed, defineComponent, getCurrentInstance, onMounted, reactive, ref } from 'vue'
  export default defineComponent({
    name: 'UserList',
    setup() {
      const searchKey = ref('')
      const active = ref(1)
      const userCommon = useCommonStore()
      const userForm = ref<typeof Form>()
      const balanceForms = ref<typeof Form>()
      const departMentList: any = ref([])
      const roleList: any = ref([])
      const treeData: any = ref([])
      const treeData2: any = ref([])
      const treeData3: any = ref([])
      const selectList: any = ref([])
      const selectList2: any = ref([])
      const selectList3: any = ref([])
      const setTreeid = ref()
      const quan = ref(false)
      const quan2 = ref(false)
      const quan3 = ref(false)
      const form = reactive({
        name: '',
        close: '',
        addTime: '',
        endTime: '',
      })
      interface subForm {
        id: any
        name: string
        sort: number
        close: boolean
        remarks: string
      }
      const subForm: subForm = reactive({
        id: '',
        name: '',
        sort: 0,
        close: false,
        remarks: '', //备注
      })
      const banlanceForm: any = reactive({
        type: '0',
        balance: 0,
        remarks: '',
      })
      const modalDialog = ref<ModalDialogType | null>(null)
      const dialogTitle = ref()
      const table = useTable()
      const rowKey = useRowKey('id')
      const pagination = usePagination(doRefresh)
      const { selectedRowKeys } = useRowSelection()
      const tableColumns: any = reactive({
        list: [
          {
            title: '角色ID',
            key: 'id',
            dataIndex: 'id',
            checked: true,
            width: 120,
          },
          {
            title: '角色名称',
            key: 'name',
            dataIndex: 'name',
            width: 180,
          },
          // {
          //   title: '排序',
          //   key: 'sort',
          //   dataIndex: 'sort',
          //   checked: true,
          //   width: 120,
          // },
          {
            title: '状态',
            key: 'close',
            dataIndex: 'close',
            checked: true,
            width: 120,
          },
          {
            title: '创建时间',
            key: 'createTime',
            dataIndex: 'createTime',
            checked: true,
            width: 190,
          },
          {
            title: '操作',
            key: 'actions',
            dataIndex: 'actions',
            align: 'center',
            checked: true,
            width: 150,
          },
        ],
      })
      const expandAllFlag = ref(true)
      const tableLoading = ref(true)
      const btnLoading = ref(false)
      const visible = ref(false)
      const balancevisible = ref(false)
      const loadingTree = ref(false)
      const loading = ref(false)
      const list = ref([])

      const exportLists = () => {
        loading.value = true
        userCommon
          .downLoads(exportRoleList, form, '角色列表')
          .then(() => {
            loading.value = false
          })
          .catch(() => {
            loading.value = false
          })
      }
      const routers = ref('')
      const sys = (val: any) => {
        routers.value = val.route
        treeData.value.forEach((item: any) => {
          if (item.children) {
            item.children.forEach((items: any) => {
              if (items.route == val.route) {
                items.show = true
              } else {
                items.show = false
              }
            })
          }
        })
      }
      function quanFn() {
        if (active.value == 1) {
          quan.value = !quan.value
          if (quan.value == false) {
            selectList.value = []
          } else {
            selectList.value = []
            treeData.value.forEach((item: any) => {
              if (item.children) {
                item.children.forEach((items: any) => {
                  if (item.children) {
                    items.children.forEach((itema: any) => {
                      selectList.value.push(itema.route)
                    })
                  }
                })
              }
            })
          }
        } else if (active.value == 2) {
          quan2.value = !quan2.value
          if (quan2.value == false) {
            selectList2.value = []
          } else {
            selectList2.value = []
            treeData2.value.forEach((item: any) => {
              if (item.children) {
                item.children.forEach((items: any) => {
                  if (item.children) {
                    items.children.forEach((itema: any) => {
                      selectList2.value.push(itema.route)
                    })
                  }
                })
              }
            })
          }
        } else if (active.value == 3) {
          quan3.value = !quan3.value
          if (quan3.value == false) {
            selectList3.value = []
          } else {
            selectList3.value = []
            treeData3.value.forEach((item: any) => {
              selectList3.value.push(item.route)
              // if (item.children) {
              //   item.children.forEach((items: any) => {
              //     if (item.children) {
              //       items.children.forEach((itema: any) => {
              //         selectList3.value.push(itema.route)
              //       })
              //     }
              //   })
              // }
            })
          }
        }
      }
      const treeData2Key = ref([])
      function expands(val: any, val1: any) {
        console.log(val)
        console.log(val1)
        treeData2Key.value = val
      }
      function zhanFn() {
        if (active.value == 1) {
          if (manuallyExpandedKeys.value.length > 0) {
            manuallyExpandedKeys.value = []
          } else {
            manuallyExpandedKeys.value = []
            treeData.value.forEach((item: any) => {
              manuallyExpandedKeys.value.push(item.route)
              if (item.children) {
                item.children.forEach((items: any) => {
                  manuallyExpandedKeys.value.push(items.route)
                })
              }
            })
          }
        } else if (active.value == 2) {
          if (treeData2Key.value.length > 0) {
            treeData2Key.value = []
          } else {
            treeData2Key.value = []
            treeData2.value.forEach((item: any) => {
              treeData2Key.value.push(item.route)
              if (item.children) {
                item.children.forEach((items: any) => {
                  treeData2Key.value.push(items.route)
                })
              }
            })
          }
        } else if (active.value == 3) {
        }
      }

      function fanFn() {
        if (active.value == 1) {
          list.value = []
          const lists = selectList.value
          treeData.value.forEach((item: any) => {
            if (item.children) {
              item.children.forEach((items: any) => {
                if (item.children) {
                  items.children.forEach((itema: any) => {
                    if (lists.length == 0) {
                      list.value.push(itema.route)
                    } else {
                      const index = lists.indexOf(itema.route)
                      if (index > -1) {
                        lists.splice(index, 1) // 移除已存在的元素
                      } else {
                        list.value.push(itema.route) // 添加不存在的元素
                      }
                    }
                  })
                }
              })
            }
          })
          selectList.value = list.value
        } else if (active.value == 2) {
          list.value = []
          const lists = selectList2.value
          treeData2.value.forEach((item: any) => {
            if (item.children) {
              item.children.forEach((items: any) => {
                if (item.children) {
                  items.children.forEach((itema: any) => {
                    if (lists.length == 0) {
                      list.value.push(itema.route)
                    } else {
                      const index = lists.indexOf(itema.route)
                      if (index > -1) {
                        lists.splice(index, 1) // 移除已存在的元素
                      } else {
                        list.value.push(itema.route) // 添加不存在的元素
                      }
                    }
                  })
                }
              })
            }
          })
          selectList2.value = list.value
        } else if (active.value == 3) {
          list.value = []
          const lists = selectList3.value
          treeData3.value.forEach((item: any) => {
            if (lists.length == 0) {
              list.value.push(item.route)
            } else {
              const index = lists.indexOf(item.route)
              if (index > -1) {
                lists.splice(index, 1) // 移除已存在的元素
              } else {
                list.value.push(item.route) // 添加不存在的元素
              }
            }
            // if (item.children) {
            //   item.children.forEach((items: any) => {
            //     if (item.children) {
            //       items.children.forEach((itema: any) => {
            //         if (lists.length == 0) {
            //           list.value.push(itema.route)
            //         } else {
            //           const index = lists.indexOf(itema.route)
            //           if (index > -1) {
            //             lists.splice(index, 1) // 移除已存在的元素
            //           } else {
            //             list.value.push(itema.route) // 添加不存在的元素
            //           }
            //         }
            //       })
            //     }
            //   })
            // }
          })
          selectList3.value = list.value
        }
      }
      function onSelect(newSelectedKeys: any, event: any) {
        console.log('select: ', newSelectedKeys, event)
      }
      function onCheck(newCheckedKeys: any, event: any) {
        console.log('check: ', newCheckedKeys, event)
      }
      function handleBeforeOkBan() {
        console.log([...selectList.value, ...selectList2.value, ...selectList3.value])
        btnLoading.value = true
        http
          .post({
            url: postSetRole + '?id=' + setTreeid.value + '&defaultRoute=' + routers.value,
            data: () => {
              return [...selectList.value, ...selectList2.value, ...selectList3.value]
            },
          })
          .then((res) => {
            btnLoading.value = false
            if (res.code == 0) {
              Message.success(res.msg)
              balancevisible.value = false
              doRefresh()
            } else {
              Message.error(res.msg)
            }
          })
      }
      const handleBeforeOk = () => {
        userForm.value?.validate().then((error: any) => {
          if (!error) {
            btnLoading.value = true
            if (dialogTitle.value == '新建角色') {
              http
                .post({
                  url: postAddRole,
                  data: () => {
                    return {
                      ...subForm,
                    }
                  },
                })
                .then((res) => {
                  btnLoading.value = false
                  if (res.code == 0) {
                    Message.success(res.msg)
                    visible.value = false
                    doRefresh()
                  } else {
                    Message.error(res.msg)
                  }
                })
            } else if (dialogTitle.value == '编辑角色')
              http
                .post({
                  url: postUpdateRole,
                  data: () => {
                    return {
                      ...subForm,
                    }
                  },
                })
                .then((res) => {
                  btnLoading.value = false
                  if (res.code == 0) {
                    Message.success(res.msg)
                    visible.value = false
                    doRefresh()
                  } else {
                    Message.error(res.msg)
                  }
                })
          } else {
            console.log(btnLoading.value)
          }
        })
      }
      const arr: any = ref([])
      const digui = (arry: any) => {
        for (let item of arry) {
          if (item.route == setTreeid.value.defaultRoute) {
            item.show = true
          }
          if (!item.api) {
            digui(item.children)
          } else {
            if (item.distribution == true) {
              arr.value.push(item.route)
            }
          }
        }
      }
      const arr2: any = ref([])
      const digui2 = (arry: any) => {
        for (let item of arry) {
          if (!item.api) {
            digui2(item.children)
          } else {
            if (item.distribution == true) {
              arr2.value.push(item.route)
            }
          }
        }
      }
      const arr3: any = ref([])
      const digui3 = (arry: any) => {
        for (let item of arry) {
          if (!item.api) {
            digui3(item.children)
          } else {
            if (item.distribution == true) {
              arr3.value.push(item.route)
            }
          }
        }
      }

      const showTree = (item: any) => {
        loadingTree.value = true
        balancevisible.value = true
        setTreeid.value = item.id
        active.value = 1
        if (item.defaultRoute) {
          routers.value = item.defaultRoute
        } else {
          routers.value = '/home/index'
        }
        console.log(active.value)
        http
          .get({
            url: getTree,
            data: () => {
              return {
                id: item.id,
              }
            },
          })
          .then((res) => {
            console.log(res)
            if (res.code == 0) {
              loadingTree.value = false
              res.data.menus.forEach((item: any) => {
                item.show = 2
                if (item.children) {
                  item.children.forEach((items: any) => {
                    if (items.route == routers.value) {
                      items.show = true
                    } else {
                      items.show = false
                    }
                  })
                }
              })

              treeData.value = res.data.menus
              treeData2.value = res.data.plugins
              treeData3.value = res.data.others
              selectList.value = []
              selectList2.value = []
              selectList3.value = []
              digui(res.data.menus)
              selectList.value = arr.value
              digui2(res.data.plugins)
              selectList2.value = arr2.value
              digui3(res.data.others)
              selectList3.value = arr3.value
              console.log(treeData.value)
            }
          })
      }
      const handleCancel = () => {
        userForm.value?.resetFields()
        visible.value = false
      }
      const handleCancelBan = () => {
        treeData.value = []
        treeData2.value = []
        treeData3.value = []
        arr.value = []
        arr2.value = []
        arr3.value = []
        routers.value = ''
        active.value = 1
        balancevisible.value = false
      }
      function doRefresh(value?: number) {
        // eslint-disable-next-line prettier/prettier
        tableLoading.value = true
        if (value) {
          pagination.page = value
        }
        http
          .get({
            url: getRoleLists,
            data: () => {
              return {
                page: pagination.page,
                size: pagination.pageSize,
                ...form,
              }
            },
          })
          .then((res) => {
            tableLoading.value = false
            table.handleSuccess(res.data.list)
            pagination.setTotalSize((res.data as any).totalSize)
          })
          .catch(console.log)
      }
      const serchForm = ref<typeof Form>()
      const resetSeach = () => {
        serchForm.value?.resetFields()
        doRefresh(1)
      }
      function onAddItem() {
        visible.value = true
        dialogTitle.value = '新建角色'
        subForm.name = ''
        subForm.id = ''
        subForm.close = false
        subForm.sort = 0
        subForm.remarks = ''
        modalDialog.value?.toggle()
      }
      function onUpdate(item: any) {
        dialogTitle.value = '编辑角色'
        subForm.name = item.name
        subForm.id = item.id
        subForm.close = item.close
        subForm.sort = item.sort
        subForm.remarks = item.remarks
        visible.value = true
      }
      function onDeleteItem(item: any) {
        Modal.warning({
          title: '操作确认',
          content: '确定要删除此角色吗？',
          cancelText: '取消',
          titleAlign: 'start',
          hideCancel: false,
          okText: '删除',
          onOk: () => {
            http
              .get({
                url: getdelRole,
                data: () => {
                  return {
                    id: item.id,
                  }
                },
              })
              .then((res) => {
                if (res.code == 0) {
                  Message.success(res.msg)
                  doRefresh()
                } else {
                  Message.error(res.msg)
                }
              })
              .catch(console.log)
          },
        })
      }

      function onUpdateBorder(isBordered: boolean) {
        table.bordered.value = isBordered
      }
      function onUpdateStriped(isStriped: boolean) {
        table.striped.value = isStriped
      }

      function tab(val: any) {
        console.log(val)
        active.value = val
      }

      onMounted(async () => {
        table.tableHeight.value = await useTableHeight(getCurrentInstance())
        doRefresh()
      })
      // 记录用户手动操作的展开状态
      const manuallyExpandedKeys = ref([])

      const expandedKeys = computed(() => {
        if (!searchKey.value) {
          return manuallyExpandedKeys.value
        }
        const keys = new Set([...manuallyExpandedKeys.value])

        const findParentKeys = (data, targetKey) => {
          for (const item of data) {
            if (item.route === targetKey) {
              return true
            }
            if (item.children) {
              if (findParentKeys(item.children, targetKey)) {
                keys.add(item.route)
                return true
              }
            }
          }
          return false
        }

        const loop = (data) => {
          data.forEach((item) => {
            console.log(item)
            if (item.name.toLowerCase().indexOf(searchKey.value.toLowerCase()) > -1) {
              keys.add(item.route)
              findParentKeys(treeData.value, item.route)
            }
            if (item.children) {
              loop(item.children)
            }
          })
        }

        loop(treeData.value)
        return Array.from(keys)
      })

      // 合并搜索展开的节点和用户手动展开的节点
      const mergedExpandedKeys = computed(() => {
        return expandedKeys.value
      })

      // 处理节点展开/折叠事件
      const handleExpand = (expandedKeys, { expanded }) => {
        if (expanded) {
          console.log(1)
          manuallyExpandedKeys.value = [
            ...new Set([...manuallyExpandedKeys.value, ...expandedKeys]),
          ]
        } else {
          manuallyExpandedKeys.value = expandedKeys
        }
        console.log(expandedKeys)
      }

      function getMatchIndex(title: any) {
        if (!searchKey.value) return -1
        return title.toLowerCase().indexOf(searchKey.value.toLowerCase())
      }
      return {
        getMatchIndex,
        handleExpand,
        mergedExpandedKeys,
        manuallyExpandedKeys,
        searchKey,
        selectList,
        selectList2,
        selectList3,
        visible,
        balancevisible,
        banlanceForm,
        btnLoading,
        departMentList,
        roleList,
        loadingTree,
        loading,
        serchForm,
        handleBeforeOk,
        handleBeforeOkBan,
        handleCancel,
        handleCancelBan,
        dialogTitle,
        doRefresh,
        tableLoading,
        subForm,
        userForm,
        balanceForms,
        form,
        ...table,
        rowKey,
        selectedRowKeys,
        expandAllFlag,
        tableColumns,
        pagination,
        treeData,
        treeData2,
        treeData3,
        onSelect,
        onCheck,
        exportLists,
        showTree,
        onUpdate,
        onAddItem,
        resetSeach,
        onDeleteItem,
        sys,
        onUpdateBorder,
        onUpdateStriped,
        active,
        quanFn,
        tab,
        fanFn,
        zhanFn,
        treeData2Key,
        expands,
      }
    },
  })
</script>
<style lang="less" scoped>
  :deep(.arco-modal) {
    .arco-modal-footer {
      text-align: right !important;
    }
  }
  :deep(.arco-modal-header .arco-modal-title) {
    display: flex;
    justify-content: flex-start !important;
  }
  :deep(.arco-table-td-content button) {
    padding: 0px !important;
    margin-right: 8px;
    background: none !important;
  }
</style>
